import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:cbec_app/components/common/sort_flitter_box.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/components/goods/goods_item.dart';
import 'package:cbec_app/pages/classify/controller/classify_filter_ctr.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../utils/Tools.dart';
import '../../goods/binding/goods_detail_binding.dart';
import '../../goods/view/goods_detail_page.dart';

///分类筛选页
class ClassifyFilterPage extends GetView<ClassifyFilterController> {
  const ClassifyFilterPage({super.key});
  @override
  Widget build(BuildContext context) {
    return GetBuilder<ClassifyFilterController>(
      builder: (controller) {
        return BasePage(navBgColor: Colors.white, iconType: IconType.back, isSearch: true, searchType: SearchStyleType.onlySearch, isDisable: true, routeName: Routes.search, placeholder: '输入关键字搜索', refreshController: controller.baseRefreshCtr, enablePullDown: true, enablePullUp: controller.isLoadData, onPageRefresh: controller.onPageRefresh, onPageLoading: controller.onPageLoading, tabBgColor: Colors.white, children: [
          Container(
            color: Tools.fromHex("#F4F4F4"),
            child: TabBar(
                tabAlignment: TabAlignment.start,
                indicatorColor: ThemeConfig.themeColor,
                dividerColor: Colors.transparent,
                labelColor: ThemeConfig.themeColor,
                controller: controller.tabCtr,
                isScrollable: true,
                tabs: controller.secondList
                    .map((item) => Tab(
                          text: item['className'],
                        ))
                    .toList()),
          ),
          SortFlitterBox(
            showFlitter: true,
            curIndex: controller.filterIndex,
            sortList: controller.filterList,
            callback: (index) {
              controller.dealFilterFiled(index);
            },
            showCallBack: (isGrid) {
              controller.changeListStyle(isGrid);
            },
          ),
          Container(
            padding: EdgeInsets.only(left: 8.w, right: 8.w, top: 10.h, bottom: 20.h),
            child: controller.isGrid ? buildWrapWidget(controller) : buildListViewWidget(controller),
          )
        ]);
      },
    );
  }

  Widget buildListViewWidget(ClassifyFilterController controller) {
    return Wrap(alignment: WrapAlignment.spaceBetween, runSpacing: 6.w, children: controller.goodsList.isNotEmpty ? controller.goodsList.map((item) => buildItemHWidget(item)).toList() : const [NotFound()]);
  }

  Widget buildItemHWidget(item) {
    return InkWell(
      onTap: () {
        final id = item['commodityId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      child: Container(
        width: double.infinity,
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: Colors.white,
        ),
        child: Row(
          children: [
            Padding(
              padding: const EdgeInsets.all(10),
              child: ClipRRect(
                borderRadius: const BorderRadius.all(Radius.circular(8)),
                child: BaseImage(
                  url: item['mainImage'],
                  height: 100.w,
                  width: 100.w,
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 30),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    RichText(
                      text: TextSpan(
                        children: [
                          WidgetSpan(
                            alignment: PlaceholderAlignment.middle, // 垂直居中对齐
                            child: goodsTypeTag(
                              getGoodsTypeName(item['commodityType']),
                              margin: const EdgeInsets.only(right: 5), // 设置右边距
                            ),
                          ),
                          TextSpan(
                            text: item['commodityName'],
                            // text: StringGenerator.generateRandomString(),
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                              color: Tools.fromHex('#3D3D3D'),
                            ),
                          ),
                        ],
                      ),
                      maxLines: 2, // 设置最大行数为 2
                      overflow: TextOverflow.ellipsis, // 超过部分显示省略号
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      runSpacing: 5.w,
                      children: [
                        for (var text in item?['discountLabel'])
                          BorderedText(
                            text: text,
                            padding: const EdgeInsets.only(left: 2, right: 2, top: 2, bottom: 2),
                            borderColor: ThemeConfig.themeColor,
                            textStyle: const TextStyle(fontSize: 11, color: ThemeConfig.themeColor),
                          ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Text('¥', style: setTextStyle(12, FontWeight.w400, ThemeConfig.themeColor)),
                        const SizedBox(width: 2),
                        if (item['price'].toString().contains('.')) ...[
                          buildPriceRichText(item['price']),
                        ] else ...[
                          Text(item['price'].toString(), style: setTextStyle(15, FontWeight.w400, ThemeConfig.themeColor)),
                        ],
                      ],
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Wrap buildWrapWidget(ClassifyFilterController controller) {
    return Wrap(
        alignment: WrapAlignment.spaceBetween,
        runSpacing: 6.w,
        children: controller.goodsList.isNotEmpty
            ? controller.goodsList
                .map((item) => GoodsItem(
                      goodsInfo: item,
                    ))
                .toList()
            : const [NotFound()]);
  }

  Widget buildPriceRichText(double price) {
    // 将价格转换为保留两位小数的字符串
    String priceStr = price.toStringAsFixed(2); // e.g., "123.45"
    List<String> parts = priceStr.split('.'); // 分离整数和小数部分

    return RichText(
      text: TextSpan(
        style: const TextStyle(color: ThemeConfig.themeColor), // 设置默认颜色
        children: [
          TextSpan(
            text: parts[0], // 整数部分
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const TextSpan(
            text: '.', // 小数点
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w400,
            ),
          ),
          TextSpan(
            text: parts[1], // 小数部分
            style: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }
}
